import {useState} from 'react'
import {connect, ConnectedProps} from 'react-redux'
import {
  incrementAction,
  decrementAction,
  incrementAsyncAction
} from '../../redux/actions/counter'
import { RootState } from '../../redux/store'

// 执行conect返回一个新函数
const connector = connect(
  (state: RootState) => ({count: state.counter.count}),
  {
    dispatchIncrement: incrementAction,
    dispatchDecrement: decrementAction,
    dispatchIncmentAsync: incrementAsyncAction
  }
)

type Props = ConnectedProps<typeof connector>

function Counter({
  count,
  dispatchIncrement,
  dispatchDecrement,
  dispatchIncmentAsync
}: Props) {
  const [num, setNum] = useState(1)

  function increment () {
    dispatchIncrement(num)
  }
  function decrement () {
    dispatchDecrement(num)
  }
  function incrementIfOdd () {
    if (count%2===1) {
      increment()
    }
  }
  function incrementAsync () {
    dispatchIncmentAsync(num)
  }

  return (
    <>
      <h3>点击次数: {count}</h3>
      <select value={num} onChange={e => setNum(+e.target.value)}>
        <option value="1" key="a">1</option>
        <option value="2" key="b">2</option>
        <option value="3" key="c">3</option>
      </select>
      <button onClick={increment}>增加</button>
      <button onClick={decrement}>减少</button>
      <button onClick={incrementIfOdd}>奇数增加</button>
      <button onClick={incrementAsync}>延迟1S增加</button>
    </>
  )
}

export default connector(Counter) // 接收UI组件执行返回容器组件